<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    width="90%"
    :mask-closable="false"
    :modal-style="{ maxWidth: '600px' }"
    @before-ok="save"
    @close="close"
  >
    <a-form ref="FormRef" :model="form" :rules="rules" size="medium" auto-label-width>
      <a-form-item label="用户名" field="realName">
        <a-input
          v-model.trim="form.realName"
          placeholder="请输入用户名"
          allow-clear
          :disabled="form.disabled"
          :max-length="10"
        ></a-input>
      </a-form-item>

      <a-form-item label="手机号码" field="mobile">
        <a-input v-model.trim="form.mobile" placeholder="请输入手机号码" allow-clear :max-length="11"></a-input>
      </a-form-item>

      <a-form-item label="密码" field="password">
        <a-input-password
          v-model.trim="form.password"
          placeholder="不设置默认为手机号后6位"
          allow-clear
          :disabled="form.disabled"
          :max-length="10"
        ></a-input-password>
      </a-form-item>

      <a-form-item label="邮箱" field="email">
        <a-input v-model.trim="form.email" placeholder="请输入邮箱" allow-clear :max-length="30"></a-input>
      </a-form-item>

      <a-form-item label="角色" field="roleIds" :disabled="form.disabled">
        <a-select
          v-model="form.roleIds"
          :options="roleOptions"
          placeholder="请选择所属角色"
          multiple
          allow-clear
          :allow-search="{ retainInputValue: true }"
        />
      </a-form-item>
      <a-form-item label="状态" field="status">
        <a-switch
          type="round"
          v-model="form.status"
          :checked-value="1"
          :unchecked-value="0"
          checked-text="正常"
          unchecked-text="禁用"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { type FormInstance, Message } from '@arco-design/web-vue'
import * as Regexp from '@/utils/regexp'
import { getSystemUserDetail, createSystemUser, modifySystemUser } from '@/apis'
import { useRole } from '@/hooks/app'
import { useForm } from '@/hooks'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { roleList, getRoleList } = useRole()
getRoleList()
const roleOptions = computed(() => roleList.value.map((i) => ({ label: i.roleName, value: i.id })))
const FormRef = ref<FormInstance>()
const userId = ref('')
const isEdit = computed(() => !!userId.value)
const title = computed(() => (isEdit.value ? '编辑用户' : '新增用户'))
const visible = ref(false)

const { form, resetForm } = useForm({
  id: '',
  realName: '', // 用户名
  mobile: '', // 手机号
  email: '', // 邮箱
  password: '',
  roleIds: [] as string[], // 角色(可能多个)
  status: 1 as Status, // 状态 0禁用 1启用(正常)
  disabled: false // 如果 type===1 这为 true, 主要作用是列表复选框禁用状态
})

const rules: FormInstance['rules'] = {
  mobile: [
    { required: true, message: '请输入手机号' },
    { match: Regexp.Phone, message: '手机号格式不正确' }
  ],
  realName: [
    { required: true, message: '请输入昵称' },
    { min: 2, max: 10, message: '长度在 2 - 10个字符' }
  ],
  email: [{ match: Regexp.Email, message: '邮箱格式不正确' }],
  roleIds: [{ required: true, message: '请选择角色' }],
  status: [{ required: true, message: '请选择状态' }]
}

const add = () => {
  userId.value = ''
  visible.value = true
}

const edit = async (id: string) => {
  visible.value = true
  userId.value = id
  const res = await getSystemUserDetail(id)
  Object.assign(form, res.data)
}

const close = () => {
  FormRef.value?.resetFields()
  resetForm()
}

defineExpose({ add, edit })

const save = async () => {
  try {
    const obj = await FormRef.value?.validate()
    if (obj) return false
    if (form.id) {
      await modifySystemUser(form)
    } else {
      await createSystemUser(form)
    }
    Message.success('保存成功')
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}
</script>
